<template>
  <div>
    <el-card class="box-card">
      <el-button
        type="primary"
        icon="ele-Plus"
        @click="showAddOrPutTrademarkDialog({ id: 0, tmName: '', logoUrl: '' })"
        >添加</el-button
      >
      <el-table
        :data="trademarkList"
        border
        class="table-card"
        v-loading="loading"
        element-loading-text="Loading..."
        row-key="id"
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column prop="tmName" label="品牌名称" align="center" />
        <el-table-column prop="name" label="品牌LOGO">
          <template #default="{ row }">
            <el-image
              style="width: 100px; height: 100px"
              :src="row.logoUrl"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" v-slot="{ row }">
          <el-button
            title="修改"
            type="warning"
            icon="ele-Edit"
            size="small"
            @click="showAddOrPutTrademarkDialog(row)"
          ></el-button>
          <el-button
            title="删除"
            type="danger"
            icon="ele-Delete"
            size="small"
            @click="deleteTrademark(row)"
          ></el-button>
        </el-table-column>
      </el-table>
      <div class="demo-pagination-block">
        <el-pagination
          class="trademark-pagination"
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[4, 8, 12]"
          layout="prev, pager, next, jumper,sizes,total"
          :total="total"
          @size-change="GetBaseTrademark"
          @current-change="GetBaseTrademark"
        />
      </div>
      <el-dialog
        v-model="dialogVisible"
        :title="trademarkFormData.id ? '修改品牌' : '添加品牌'"
      >
        <el-form
          label-width="100px"
          ref="trademarkFormRef"
          :model="trademarkFormData"
          :rules="trademarkFormRules"
        >
          <el-form-item label="品牌名称" prop="tmName">
            <el-input
              placeholder="请输入品牌名称"
              v-model="trademarkFormData.tmName"
            />
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              :action="`${baseURL}/admin/product/fileUpload`"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="trademarkFormData.logoUrl"
                :src="trademarkFormData.logoUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传jpg/png文件，且不超过250kb
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addTradeMark">确定</el-button>
            <el-button type="primary" @click="dialogVisible = false"
              >取消</el-button
            >
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts">
export default {
  name: "LTrademark",
};
</script>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, FormInstance, FormRules } from "element-plus";
import type { ITrademarkList, ITrademark } from "@/api/product/model/trademark"; // 泛型就要用type
import {
  getBaseTrademark,
  getSaveTrademark,
  getDeleteTrademark,
  getPutTrademark,
} from "@/api/product/trademark"; // 函数就是直接引入

// 封装一个显示对话框
const dialogVisible = ref(false);
const showAddOrPutTrademarkDialog = (row: ITrademark) => {
  dialogVisible.value = true;
  trademarkFormData.tmName = row.tmName;
  trademarkFormData.logoUrl = row.logoUrl;
  trademarkFormData.id = row.id;

  trademarkFormRef.value?.clearValidate();
};

/***************添加或修改功能********************/

// 这里是表单三步
const trademarkFormRef = ref<FormInstance>();
// reactive是响应式，如果复制，就会改变地址失去响应式
const trademarkFormData = reactive({
  id: 0,
  tmName: "",
  logoUrl: "",
});

const trademarkFormRules = reactive<FormRules>({
  tmName: [{ required: true, message: "请上传名字", trigger: "blur" }],
  logoUrl: [{ required: true, message: "请上传品牌LOGO" }],
});

const addTradeMark = async () => {
  await trademarkFormRef.value?.validate();
  const { id, tmName, logoUrl } = trademarkFormData;
  if (id) {
    await getPutTrademark(trademarkFormData);
  } else {
    await getSaveTrademark(tmName, logoUrl);
  }
  dialogVisible.value = false;
  ElMessage.success(`${id ? "修改" : "添加"}品牌成功`);
  GetBaseTrademark();
};

/************ 图片上传功能 ************/
const baseURL = import.meta.env.VITE_API_URL;
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  trademarkFormData.logoUrl = response.data;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const validImageType = ["image/jpg", "image/jpeg", "image/png"];
  if (!validImageType.includes(rawFile.type)) {
    ElMessage.error("图片类型上传错误哦~~~");
    return false;
  } else if (rawFile.size / 1024 > 250) {
    ElMessage.error("图片超过了250kb哦~~");
    return false;
  }
  return true;
};

/**************** 删除功能 *********************/
const deleteTrademark = (row: ITrademark) => {
  ElMessageBox.confirm(`确定要删除 ${row.tmName} 吗`, "提示", {
    cancelButtonText: "取消",
    confirmButtonText: "确认",
    type: "warning",
  }).then(async () => {
    await getDeleteTrademark(row.id),
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    GetBaseTrademark();
  });
};

/******** 渲染分页 ************/
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(4);
const total = ref(0);
// const handleSizeChange = () => {
//   GetBaseTrademark();
// };
// const handleCurrentChange = () => {
//   GetBaseTrademark();
// };
// onMounted(() => {
//   GetBaseTrademark();
// });

const trademarkList = ref<ITrademarkList>([]);
const GetBaseTrademark = async (
  page: number = currentPage.value,
  limit: number = pageSize.value
) => {
  loading.value = true;
  const result = await getBaseTrademark(page, limit);
  trademarkList.value = result.records;
  total.value = result.total;
  pageSize.value = limit;
  currentPage.value = page;
  loading.value = false;
};
onMounted(GetBaseTrademark);
</script>

<style scoped lang="scss">
.table-card {
  margin: 17px 0;
}
.trademark-pagination :deep() {
  .el-pagination__sizes {
    position: absolute;
    right: 120px;
  }

  .el-pagination__total {
    position: absolute;
    right: 40px;
  }
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
